<!-- 排考(操作页面) -->
<template>
    <div>
        <div style="height: 30px;">
            <el-breadcrumb style="float: left;" separator="/">
                <el-breadcrumb-item :to="{ path: '/competitionList' }">
                    <span @click="reback">{{ $t('arrangingExaminations.examinationSchedulingOperation') }}</span>
                </el-breadcrumb-item>
                <el-breadcrumb-item>{{ $t('arrangingExaminations.arranging') }}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>

        <el-card v-loading="loading" shadow="never" body-style="padding: 10px;">
            <div style="padding:15px 15px 0 15px; display:flex;" class="row-bg" justify="space-between">
                <h2 class="condition-title" style="float:left; width:100%;">
                    <span>{{ this.jsTitle }}</span> - {{ $t('arrangingExaminations.arranging') }}（{{ $t('arrangingExaminations.currentExam') }}<span>{{ this.dataNumber[0] }}</span>{{ $t('arrangingExaminations.people') }}，{{ $t('arrangingExaminations.arrangAlready') }}<span>{{ this.dataNumber[1] }}</span>{{ $t('arrangingExaminations.people') }}。）{{ $t('arrangingExaminations.examStartTime') }}{{ this.dataObj.examStart }},{{ $t('arrangingExaminations.examEndTime') }}{{ this.dataObj.examEnd }}
                </h2>
                <el-button style="float:right; margin-left:10px; padding-right:9px;" @click="reback">{{ $t('arrangingExaminations.goBack') }}</el-button>
            </div>

            <condition-card @reset="resetSearch" @search="onSearch" label-position="right" label-width="170px">
                <!-- 第一行 -->
                <el-row :gutter="24" style="height: 50px;">
                    <!-- 教室名称 -->
                    <el-col :span="8">
                        <el-form-item :label="$t('arrangingExaminations.classRoomName')">
                            <el-input v-model.trim="query.name" :placeholder="$t('arrangingExaminations.pleaseEnter')" clearable style="width:100%"></el-input>
                        </el-form-item>
                    </el-col>
                    <!-- 校区 -->
                    <el-col :span="8">
                        <el-form-item :label="$t('arrangingExaminations.campus')">
                            <DictSelect
                                :plzSelect="true"
                                v-model="query.campus"
                                :data="options.campus"
                                :clearable="true"
                                @change="handelCampusChang">
                            </DictSelect>
                        </el-form-item>
                    </el-col>
                    <!-- 教学楼 -->
                    <el-col :span="8">
                        <el-form-item :label="$t('arrangingExaminations.academicBuilding')">
                            <DictSelect
                                :plzSelect="true"
                                v-model="query.towerCode"
                                :clearable="true"
                                :filterable="true"
                                :data="teachingBuildingArr">
                            </DictSelect>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第二行 -->
                <el-row :gutter="24" style="height: 50px;">
                    <!-- 楼层 -->
                    <el-col :span="8">
                        <el-form-item :label="$t('arrangingExaminations.floor')">
                            <el-input
                                onkeyup="value=value.replace(/[^\d]/g,'')" 
                                type="text"
                                v-model="query.floor"
                                :placeholder="$t('arrangingExaminations.pleaseEnterInteger')"
                                @keypress.native="checkNum"
                                maxlength="5" />
                        </el-form-item>
                    </el-col>
                   <!-- 使用小节 -->
                    <el-col :span="8">
                        <el-form-item :label="$t('arrangingExaminations.usingSections')">
                            <el-row type="flex" justify="center" align="middle">
                                <el-input 
                                    disabled
                                    type="text" 
                                    v-model="query.timeStart"
                                    @keypress.native="checkNum"
                                    @blur="checkTimeValue($event,1)"
                                    onkeyup="value=value.replace(/[^\d]/g,'')" 
                                    :placeholder="$t('message.mustNumber')"
                                    maxlength="5" />  
                                <span style="margin: 0 10px;">~</span>
                                <el-input 
                                    disabled
                                    type="text" 
                                    v-model="query.timeEnd"
                                    @keypress.native="checkNum"
                                    @blur="checkTimeValue($event,2)"
                                    onkeyup="value=value.replace(/[^\d]/g,'')" 
                                    :placeholder="$t('message.mustNumber')"
                                    maxlength="5" /> 
                            </el-row>
                        </el-form-item>
                    </el-col>
                    <!-- 教学周 -->
                    <el-col :span="8">
                        <el-form-item :label="$t('arrangingExaminations.teachingWeek')">
                            <el-row type="flex" justify="center" align="middle">
                                <el-input 
                                    disabled
                                    type="text" 
                                    style="width: 100%;"
                                    v-model="query.weekStart"
                                    @keypress.native="checkNum"
                                    @blur="checkWeekValue($event,1)" 
                                    onkeyup="value=value.replace(/[^\d]/g,'')" 
                                    :placeholder="$t('message.mustNumber')"
                                    maxlength="5" />
                                <span style="margin: 0 10px;">~</span>
                                <el-input 
                                    disabled
                                    type="text" 
                                    style="width: 100%;"
                                    v-model="query.weekEnd"
                                    @keypress.native="checkNum"
                                    @blur="checkWeekValue($event,2)" 
                                    onkeyup="value=value.replace(/[^\d]/g,'')" 
                                    :placeholder="$t('message.mustNumber')"
                                    maxlength="5" />
                            </el-row>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第三行 -->
                <el-row :gutter="24" style="height: 50px;">
                    <!-- 学年学期 -->
                    <el-col :span="8">
                        <el-form-item :label="$t('arrangingExaminations.semester')">
                            <CalendarSelect disabled v-model="query.calendarId" :all="true" :defaulted ="true" @change="changeCalendar" @load-done="calendarLoadDone"></CalendarSelect>
                        </el-form-item>
                    </el-col>
                    <!-- 教室使用星期 -->
                    <el-col :span="8">
                        <el-form-item :label="$t('arrangingExaminations.classroomUseWeek')">
                            <el-row type="flex" justify="center" align="middle">
                                <DictSelect
                                    disabled
                                    :plzSelect="true"
                                    v-model="query.dayOfWeekStart"
                                    :data="options.week"
                                    :clearable="true"
                                    :exclude="dayOfWeekStartExclude"
                                    @change="changeDayOfWeekEndExclude">
                                </DictSelect>
                                <span style="margin: 0 10px;">~</span>
                                <DictSelect
                                    disabled
                                    :plzSelect="true"
                                    v-model="query.dayOfWeekEnd"
                                    :data="options.week"
                                    :clearable="true"
                                    :exclude="dayOfWeekEndExclude"
                                    @change="changeDayOfWeekStartExclude">
                                </DictSelect>
                            </el-row>
                        </el-form-item>
                    </el-col>
                </el-row>
            </condition-card>


            <div style="padding:15px; display:flex;" class="row-bg" justify="space-between">
                <h2 class="condition-title" style="float:left; width:100%">
                    {{ $t('arrangingExaminations.classroomList') }}
                </h2>
                <el-button type="primary" style="float:right; margin-left:10px;" @click="allAddition">{{ $t('arrangingExaminations.addition') }}</el-button> <!-- 添加按钮 -->
            </div>

            <!-- 中间的表格 -->
            <EduTable
                :order="true"
                :selection="true"
                :data="idleRoomList.data"
                :total="idleRoomList.total"
                :pageSize="query.pageSize_"
                :current-page="query.pageNum_"
                @page-change="pageChange"
                @selection-change="handleSelectionChange"
            >
                <el-table-column :label="$t('classroom.name')"><template slot-scope="scope">{{scope.row.name}}</template></el-table-column><!-- 教室名称 -->
                <el-table-column :label="$t('classroom.tower')"><template slot-scope="scope">{{scope.row.towerName}}</template></el-table-column><!-- 教学楼 -->
                <el-table-column :label="$t('classroom.floor')"><template slot-scope="scope">{{scope.row.floor}}</template></el-table-column><!-- 楼层 -->
                <el-table-column :label="$t('classroom.campus')"><template slot-scope="scope">{{scope.row.campusI18n}}</template></el-table-column><!-- 校区 -->
                <el-table-column :label="$t('classroom.type')"><template slot-scope="scope">{{scope.row.typeI18n}}</template></el-table-column><!-- 教室类型 -->
                <el-table-column :label="$t('classroom.examCapacity')"><template slot-scope="scope">{{scope.row.examCapacity}}</template></el-table-column><!-- 排考容量 -->
                <el-table-column :label="$t('arrangingExaminations.scheduledExamination')"><template slot-scope="scope">{{scope.row.arrangeExam?scope.row.arrangeExam:0}}</template></el-table-column><!-- 已排考 -->
                <!-- 操作 -->
                <el-table-column :label="$t('arrangingExaminations.operation')">
                    <template slot-scope="scope">
                        <el-button type="text" @click="addition(scope.row,scope.$index)">{{ $t('arrangingExaminations.addition') }}</el-button> <!-- 添加按钮 -->
                        <el-button type="text" @click="check(scope.row)">{{ $t('arrangingExaminations.check') }}</el-button> <!-- 查看按钮 -->
                    </template>
                </el-table-column>
            </EduTable>

            <div style="padding:20px 15px 20px 15px; display:flex;" class="row-bg" justify="space-between">
                <h2 class="condition-title" style="float:left; width:100%">
                    {{ $t('arrangingExaminations.selectedClassroom') }}
                </h2>
                <div style="float: right; width: 100%;">
                    <el-button style="float:right; margin-left:10px;" @click="printSignInForm">{{ $t('arrangingExaminations.printSignInForm') }}</el-button>
                    <el-button style="float:right; margin-left:10px;" @click="candidateInformationForm">{{ $t('arrangingExaminations.candidateInformationForm') }}</el-button>
                    <el-button style="float:right; margin-left:10px;" @click="printTheAdmissionCard()">{{ $t('arrangingExaminations.printTheAdmissionCard') }}</el-button>
                    <el-button style="float:right; margin-left:10px;" @click="printTheAdmissionCard('1')">{{ $t('arrangingExaminations.printTheTable') }}</el-button>
                    <el-dropdown style="float:right;" placement='bottom-start' trigger="click" @command="downloadFile">
                        <el-button type="primary">{{$t('arrangingExaminations.arranging')}}<i class="el-icon-arrow-down el-icon--right"></i></el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="successive">{{ $t('arrangingExaminations.arrangeSuccessively') }}</el-dropdown-item>
                            <el-dropdown-item command="random">{{ $t('arrangingExaminations.arrangeRandom') }}</el-dropdown-item>
                            <el-dropdown-item v-if="courseCode" command="teachClass">{{ $t('arrangingExaminations.teachClassArring') }}</el-dropdown-item><!-- 按教学班排考 -->
                            <el-dropdown-item v-if="examType == 1" command="englishComArrange">{{ $t('arrangingExaminations.englishComArrange') }}</el-dropdown-item><!-- 大英赛排考 -->
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>
            </div>


            <!-- 下面的表格 -->
            <edu-table :pagination="false" :selection='false' :order="true" :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini">
                <edu-table-column :label="$t('classroom.name')" prop="name"></edu-table-column> <!-- 教室名称 -->
                <edu-table-column :label="$t('arrangingExaminations.campus')" prop="campusI18n"></edu-table-column> <!-- 校区 -->
                <edu-table-column :label="$t('arrangingExaminations.examSchedulingCapacity')" prop="examCapacity"></edu-table-column> <!-- 排考容量 -->
                <!-- <edu-table-column :label="$t('arrangingExaminations.scheduledExamination')" prop="arrangeExam"></edu-table-column> 已排考 -->
                <!-- 请输入考场号 -->
                <!-- onkeyup="value=value.replace(/[^\d]/g,'')" -->
                <edu-table-column :label="$t('arrangingExaminations.pleaseEnterExamRoom')" prop="roomCode">
                    <template slot-scope="scope">
                        <el-input
                            onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"
                            v-model="scope.row.roomCode"
                            maxlength="2"
                            clearable
                            :placeholder="$t('arrangingExaminations.pleaseEnterExamRoom')"
                        >
                        </el-input>
                    </template>
                </edu-table-column> 
                <!-- 操作 -->
                <edu-table-column :label="$t('arrangingExaminations.operation')" min-width="120">
                    <template slot-scope="scope">
                        <el-button type="text" @click="deleted(scope.$index)">{{ $t('arrangingExaminations.deleted') }}</el-button> <!-- 删除按钮 -->
                    </template>
                </edu-table-column>
            </edu-table>
        </el-card>

        <!-- 暂时没用到 -->
        <el-dialog :title="$t('arrangingExaminations.arrangingSuccess')" :before-close="cancel" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
            <h2>
                {{ $t('arrangingExaminations.sipingRoadCampus') }}：{{ $t('arrangingExaminations.currentRoomAccommodate') }}<span style="color: red;font-size: 20px;">{{ numbered }}</span>{{ $t('arrangingExaminations.people') }}，{{ $t('arrangingExaminations.actualNumber') }}<span style="color: red;font-size: 20px;">{{ numbered }}</span>{{ $t('arrangingExaminations.people') }}
            </h2>
            <h2>
                {{ $t('arrangingExaminations.jiadingCampus') }}：{{ $t('arrangingExaminations.currentRoomAccommodate') }}<span style="color: red;font-size: 20px;">{{ numbered }}</span>{{ $t('arrangingExaminations.people') }}，{{ $t('arrangingExaminations.actualNumber') }}<span style="color: red;font-size: 20px;">{{ numbered }}</span>{{ $t('arrangingExaminations.people') }}
            </h2>
            <div style="text-align: center; padding:inherit">
                <el-button class="distance" type="text" @click="printTheAdmissionCard">{{ $t('arrangingExaminations.printTheAdmissionCard') }}</el-button>
                <el-button class="distance" type="text" @click="candidateInformationForm">{{ $t('arrangingExaminations.candidateInformationForm') }}</el-button>
                <el-button class="distance" type="text" @click="printSignInForm">{{ $t('arrangingExaminations.printSignInForm') }}</el-button>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">{{ $t('examinationSetting.cancel') }}</el-button>
                <el-button type="primary" @click="determine">{{ $t('examinationSetting.determine') }}</el-button>
            </div>
        </el-dialog>


        <!-- 教室详细信息 -->
        <edu-dialog
            ref="classroomDetailDialog"
            class="classroomDetailDialog"
            :title="$t('classroom.classroomDetail')"
            :showButtons="false"
            >
            <room-info-details :classroomDetail="classroomDetail" />
        </edu-dialog>
    </div>
</template>
<script>
import { queryDic } from 'common/src/api/dictionary'
import UTILS from 'common/src/utils/utils'
import * as API from "common/src/api/resource/classroom"
import competitionRuleApi from 'common/src/api/competitionRegistration/competitionRegistration'
import roomInfoDetails from "common/src/views/resource/classroom/components/roomInfoDetails"
import comRegistration from 'common/src/api/competitionRegistration/comRegistration'
export default {
    name: "arrangingExaminations",
    components: {
        roomInfoDetails
    },
    props: {
        jsId: {
            type: String,
            default: ''
        },
        jsTitle: {
            type: String,
            default: ''
        },
        examType: {
            type: String,
            default: ''
        },
        isArrange: {
            type :String,
            default: ''
        },
        courseCode: {
            type: String,
            default: ''
        },
        compile: {
            type: String,
            default: ''
        },
        dataObjList: {
            type: Array,
            default: () => []   
        },
        dataObjListTwo: {
            type: Array,
            default: () => []  
        },
        mark: {
            type: String,
            default: ''
        }
    },
    data() {
        return {
            query: {
                pageNum_: 1,
                pageSize_: 20,
                type: '', // 教室类型
                campus: '', // 校区
                towerCode: '', // 教学楼
                floor: '', // 楼层
                name: '', // 教室名称
                weekStart: '', // 教学周
                weekEnd: '', // 教学周
                calendarId: '', // 学年学期
                dayOfWeekStart: '', // 教室使用星期
                dayOfWeekEnd: '', // 教室使用星期
                timeStart: '', // 使用小节
                timeEnd: '', // 使用小节
                examCapacity: 1,
                idsIn: []
            },
            defaultQuery: {
                pageNum_: 1,
                pageSize_: 20,
                type: '', // 教室类型
                campus: '', // 校区
                towerCode: '', // 教学楼
                floor: '', // 楼层
                name: '', // 教室名称
                weekStart: '', // 教学周
                weekEnd: '', // 教学周
                calendarId: '', // 学年学期
                dayOfWeekStart: '', // 教室使用星期
                dayOfWeekEnd: '', // 教室使用星期
                timeStart: '', // 使用小节
                timeEnd: '', // 使用小节
                examCapacity: 1
            },
            // 排考
            arrang: {
                competitionId: '', // 竞赛id
                classrooms: [ // 勾选的教室
                    {
                        classroomId: '',
                        roomSize: '',
                        campus: '',
                        campusName: '',
                        roomName: '',
                        roomCode: ''
                    }
                ],
                calendarId: '',
                realWeek: '',
                realWeekDay: '',
                classNodes: '',
                arrangeType: '',
                campusList: [
                    {
                        code: '',
                        name: ''
                    }
                ]
            },
            teachingBuildingArr: [], // 教学楼
            dataNumber:[],
            numbered: 222200,
            options: {
                type: [], // 教室类型
                campus: [], // 校区
                week: [
                {
                    label: "星期一",
                    value: "1",
                    disabled: true
                },
                {
                    label: "星期二",
                    value: "2",
                    disabled: true
                },
                {
                    label: "星期三",
                    value: "3"
                },
                {
                    label: "星期四",
                    value: "4"
                },
                {
                    label: "星期五",
                    value: "5"
                },
                {
                    label: "星期六",
                    value: "6"
                },
                {
                    label: "星期日",
                    value: "7"
                }
                ]
            },
            dataObj: {},
            // 勾选
            multipleSelection: [],
            // 中间表格数据
            idleRoomList: {
                data: [],
                total: 0
            },
            // 教室详情信息
            classroomDetail: {},
            currentTermCalendar:'',
            //所有校历数据
            allCalendarList:[],
            //当前学期下的总教学周
            totalWeekNumber:'',
            //可输入最大节次
            maxTime : 12,
            //可输入最小节次
            minTime : 1,
            //教室使用时间类型
            //做教室使用星期选择校验
            dayOfWeekStartExclude:[],
            dayOfWeekEndExclude:[],
            dataList: [],
            dialogFormVisible: false
        }
    },
    created() {
        // console.log(this.courseCode,'courseCode');
        this.initOptions();
        // this.getFreeClassroomInfoList();
        this.handelCampusChang(null);
    },
    mounted() {
        competitionRuleApi.getReverseCondition(this.jsId).then(res => {
            if (res.code === 200) {
                this.compile = 'arrange'
                this.dataObj = res.data
                this.query.calendarId = this.dataObj.calendarId
                this.query.weekStart = this.dataObj.realWeek 
                this.query.weekEnd = this.dataObj.realWeek
                this.query.dayOfWeekStart = this.dataObj.realWeekDay
                this.query.dayOfWeekEnd = this.dataObj.realWeekDay
                this.query.timeStart = this.dataObj.classNodes ? this.dataObj.classNodes.split(",")[0] : this.dataObj.classNodes
                this.query.timeEnd = this.dataObj.classNodes ? this.dataObj.classNodes.split(",")[1] : this.dataObj.classNodes
                this.getFreeClassroomInfoList();
            }
        })
        this.dataNumber = this.dataObjList
        // this.getFreeClassroomInfoList();
    },
    methods: {
        // 教室使用星期
        changeDayOfWeekEndExclude(val){
            let tempList = [];
            for (let index = 0; index < (parseInt(val)-1); index++) {
                tempList.push(index+1);
            }
            this.dayOfWeekEndExclude = tempList;
        },
        // 教室使用星期
        changeDayOfWeekStartExclude(val){
            let tempList = [];
            for (let index = 7; val && index > val; index--) {
                tempList.push(index);
            }
            this.dayOfWeekStartExclude = tempList;
        },
        // 学年学期
        calendarLoadDone(list){
			if(list) {
                this.allCalendarList = list;
                for (let index = 0; index < list.length; index++) {
                    const element = list[index];
                    if (element.currentTermFlag) {
                        this.currentTermCalendar = element.id;
                        this.totalWeekNumber = element.weekNum;
                        break;
                    }
                }
			}
        },
        // 每当校历发生变化，动态加载教学周总量
        changeCalendar(val){
            if (this.allCalendarList){
                this.allCalendarList.forEach(canlendar =>{
                    if(canlendar.id === val){
                    this.totalWeekNumber = canlendar.weekNum;
                    }
                })
            }
        },
        //把部门list 转换成字符串
        getDepartmentStrByList(list) {
            let str = "";
            if (list != null) {
                list.forEach(index => {
                    str += index.departmentCodeI18n + " |";
                });
                str = str.substr(0, str.length - 1);
            }
            return str;
        },
        //把用途list 转换成字符串
        getUsageStrByList(list) {
            let str = "";
            if (list != null) {
                list.forEach(index => {
                str += index.usageCodeI18n + " |";
                });
                str = str.substr(0, str.length - 1);
            }
            return str;
        },
        // 把所属部门list 转换成字符串
        getProjectStrByList(list) {
            let str = "";
            if (list != null) {
                list.forEach(index => {
                str += index.projectIdI18n + " |";
                });
                str = str.substr(0, str.length - 1);
            }
            return str;
        },
        getFreeClassroomInfoList(){
            let resTdata = []
            competitionRuleApi.getArrangeClassroomInfo(this.jsId).then(resT => {
                if (resT.code === 200) {
                    this.query.idsIn = []
                    resTdata = resT.data
                //1. 保证提交的数据中周次必须起始周和结束周要么都有值，要么都没值
                if (this.query.weekStart) {
                    if (this.query.weekEnd == "" || this.query.weekEnd == 0) {
                        this.query.weekEnd = this.totalWeekNumber;
                    }
                }
                if (this.query.weekEnd) {
                    if (this.query.weekStart == "" || this.query.weekStart == 0) {
                        this.query.weekStart = 1;
                    }
                }
                if (this.query.weekStart > 0 && this.query.weekEnd > 0 && (parseInt(this.query.weekEnd) < parseInt(this.query.weekStart))) {
                    this.$message({
                        type: "warning",
                        message: this.$t('arrangingExaminations.theStartCannotBeGreaterThanEnd')  // "筛选条件起始周次不能大于结束周次!"
                    });
                    return;
                }
                //2. 保证提交的数据中节次必须起始值和结束值要么都有值，要么都没值
                if (this.query.timeStart) {
                    if (this.query.timeEnd == "" || this.query.timeEnd == 0) {
                        this.query.timeEnd = this.maxTime;
                    }
                }
                if (this.query.timeEnd) {
                    if (this.query.timeStart == "" || this.query.timeStart == 0) {
                        this.query.timeStart = 1;
                    }
                }
                if (this.query.timeStart > 0 && this.query.timeEnd > 0 && parseInt(this.query.timeEnd) < parseInt(this.query.timeStart)) {
                    this.$message({
                        type: "warning",
                        message: this.$t('arrangingExaminations.theStartSectionCannotBeGreaterThanEndSection')  // "筛选条件起始节次不能大于结束节次!"
                    });
                    return;
                }
                resTdata.forEach(bal => {
                    this.query.idsIn.push(bal.classroomId)
                })
                API.getFreeClassroomInfoList(this.query).then(res => {
                    // 对固定使用部门数据进行处理
                    if (res && res.code == 200) {
                        _.forEach(res.data.list, item => {
                        item.departmentStr = this.getDepartmentStrByList(
                            item.fixDepartmentList
                        );
                        item.usageStr = this.getUsageStrByList(item.classroomUsageList);
                        item.projectStr = this.getProjectStrByList(item.belongDepartmentList);
                        item.fixDepartmentList = item.fixDepartmentList.map(item => {
                            return item.departmentCode;
                        });
                        item.belongDepartmentList = item.belongDepartmentList.map(item => {
                            return item.projectId;
                        });
                        item.classroomUsageList = item.classroomUsageList.map(item => {
                            return item.usageCode;
                        });
                        // if(resTdata && resTdata.length > 0) {
                        //     resTdata.forEach(bal=> {
                        //         if(bal.classroomId == item.id) {
                        //             // item.arrangeExam = bal.studentNum
                        //             this.$set(item,'arrangeExam',bal.studentNum)
                        //             console.log()
                        //         } else {
                        //             item.arrangeExam =  0
                        //         }
                        //     })
                        // } else {
                        //     item.arrangeExam = 0
                        // }
                        // this.idleRoomList.data.push(item)
                            
                         
                        });
                        if(resTdata && resTdata.length > 0) {
                            for(let j = 0; j < res.data.list.length; j++) {
                                for(let i = 0; i < resTdata.length; i++ ) {
                                    if(resTdata[i].classroomId === res.data.list[j].id) {
                                        res.data.list[j].arrangeExam = resTdata[i].studentNum
                                    } 
                                }
                            }
                        }


                        this.idleRoomList.data = res.data.list;
                        this.idleRoomList.total = res.data.total_;
                        this.query.pageSize_ = res.data.pageSize_;
                        this.query.pageNum_ = res.data.pageNum_;
                        this.multipleSelection = [];

                    }
                });
              }
            })
        },
        // 只输入数字正则
        checkNum(e) {
            let reg = /^(0|[1-9]\d*)$/;
            let num = e.target.value || "";
            let str = e.key && e.key != "Unidentified" ? e.key : num.substr(num.length - 1);
            //没有满足任何一种情况，中断执行
            if (reg.test(str)) {
                return true;
            }
            e.returnValue = false;
            return false;
        },
        // 使用小节
        checkTimeValue(e,flag) {
            let inputValue = e.target.value;
            if(inputValue > this.maxTime) {
                e.target.value = this.maxTime;
                if (flag === 1) {
                    this.query.timeStart = this.maxTime;
                } else {
                    this.query.timeEnd = this.maxTime;
                } 
            }
        },
        // 教学周
        checkWeekValue(e,flag) {
            let inputValue = e.target.value;
            if(inputValue > this.totalWeekNumber) {
                e.target.value = this.totalWeekNumber;
                if (flag === 1) {
                    this.query.weekStart = this.totalWeekNumber;
                } else {
                    this.query.weekEnd = this.totalWeekNumber;
                } 
            }
        },
        // 重置
        resetSearch() {
            // this.query = JSON.parse(JSON.stringify(this.defaultQuery));
            // 学期为当前学期
            this.query.pageNum_ = 1
            this.query.pageSize_ = 20
            this.query.name = ''
            this.query.campus = ''
            this.query.towerCode = ''
            this.query.floor = ''
            this.query.calendarId = this.currentTermCalendar;
            this.query.weekStart = this.dataObj.realWeek    
            this.query.weekEnd = this.dataObj.realWeek
            this.query.dayOfWeekStart = this.dataObj.realWeekDay
            this.query.dayOfWeekEnd = this.dataObj.realWeekDay
            this.query.timeStart = this.dataObj.classNodes.split(",")[0]
            this.query.timeEnd= this.dataObj.classNodes.split(",")[1]
            this.getFreeClassroomInfoList();
            this.handelCampusChang(null);
        },
        // 筛选
        onSearch() {
            this.getFreeClassroomInfoList();
        },
        // 返回主页面
        reback() {
            this.$emit('change-exam')
        },
        // 勾选
        handleSelectionChange(val) {
            this.multipleSelection = []
            val.forEach(item=> {
                this.multipleSelection.push(item)
            })
        },
        // 单个添加
        addition(val,index) {
            let flag = false
            if(this.dataList && this.dataList.length > 0) {
                this.dataList.forEach(data=> {
                    if(data.id === val.id) {
                        this.$message.error(this.$t('arrangingExaminations.dataAdded')) // 已经添加过该条数据
                        flag = true
                    } 
                })
            } else {
                flag = false
            }
            if(!flag) {
                this.dataList.push(val)
            }
            // console.log(this.dataList,'datalist');
        },
        // 批量添加
        allAddition() {
            if (this.multipleSelection.length > 0) {
                for(let i = 0; i<this.multipleSelection.length; i++) {
                    if(!this.dataList.includes(this.multipleSelection[i])) {
                        this.dataList.push(this.multipleSelection[i])
                    }
                }
            } else {
                this.$message({
                    type: 'warning',
                    message: this.$t('arrangingExaminations.pleaseSelectData') // 请勾选数据
                });
            }
        },
        // 删除
        deleted(index) {
            this.dataList[index].roomCode = ''
            this.dataList.splice(index,1)
        },
        // 打印签到表 zip
        printSignInForm() {
            if (this.isArrange !== null) {
                if (this.dataList.length > 0) {
                    let classrooms = []
                    this.dataList.forEach(el => {
                        classrooms.push({
                            classroomId: el.id
                        })
                    })
                    let sheet = {
                        competitionId : this.jsId,
                        classrooms: classrooms
                    }
                    competitionRuleApi.printArriveSheet(sheet).then(res => {
                        this.$message.success(this.$t('internship.successfully'));
                    })
                } else {
                    let sheet = {
                        competitionId : this.jsId,
                        classrooms: []  
                    }
                    competitionRuleApi.printArriveSheet(sheet).then(res => {
                        this.$message.success(this.$t('internship.successfully'));
                    })
                }
            } else {
                return this.$message.error(this.$t('registrationList.noExamSchedule'))
            }
        },
        // 考生信息表 excel
        candidateInformationForm() {
            // null：未排考
            if (this.isArrange !== null) {
                if (this.dataList.length > 0) {
                    let classrooms = []
                    this.dataList.forEach(el => {
                        classrooms.push({
                            classroomId: el.id
                        })
                    })
                    let info = {
                        competitionId: this.jsId,
                        classrooms: classrooms
                    }
                    competitionRuleApi.printStudentInfo(info).then(res => {
                        this.$message.success(this.$t('internship.successfully'));
                    })
                } else {
                    let info = {
                        competitionId: this.jsId,
                        classrooms: []
                    }
                    competitionRuleApi.printStudentInfo(info).then(res => {
                        this.$message.success(this.$t('internship.successfully'));
                    })
                }
            } else {
                return this.$message.error(this.$t('registrationList.noExamSchedule'))
            }
        },
        // 打印准考证/打印桌标 zip
        printTheAdmissionCard(type) {
            if (this.isArrange !== null) {
                if(this.dataList.length > 0) {
                    let classrooms = []
                    this.dataList.forEach(el => {
                        classrooms.push({
                           campusName: el.campusI18n
                        })
                    })
                    let card = {
                        printCardType: type ? type : null,
                        competitionId: this.jsId,
                        classrooms: classrooms
                    }
                    competitionRuleApi.printExamCard(card).then(res => {
                        this.$message.success(this.$t('internship.successfully'));
                    })
                } else {
                    let card = {
                        printCardType: type ? type : null,
                        competitionId: this.jsId,
                        classrooms: []
                    }
                    competitionRuleApi.printExamCard(card).then(res => {
                        this.$message.success(this.$t('internship.successfully'));
                    })
                }
            } else {
                return this.$message.error(this.$t('registrationList.noExamSchedule'))
            }
        },

        // 排考
        arranging() {
            this.dialogFormVisible = true
        },
        // 查看
        check(info) {
            this.$refs.classroomDetailDialog.open();
            let cloneInfo = _.clone(info);
            this.classroomDetail = cloneInfo;
        },
        // 分页功能
        pageChange(val) {
            this.query.pageNum_ = val.pageNum;
            this.query.pageSize_ = val.pageSize;
            if (this.mark === 200) {
                this.getFreeClassroomInfoList();
            }
        },
        // 弹框内的取消
        cancel() {
            this.dialogFormVisible = false
        },
        // 弹框内的确定
        determine() {
            this.dialogFormVisible = false
        },
        // 获取下拉框数据（数据字典）
        initOptions() {
            let data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: ["X_YX", "X_XQ", "X_JSLX", "X_GLBM"]
            };
            queryDic(data).then(res => {
                if (res.code == 200) {
                    UTILS.fillSelect(
                    {
                        campus: "X_XQ",
                        departmentCode: "X_YX",
                        type: "X_JSLX",
                        fixedDept: "X_YX",
                        dept: "X_GLBM"
                    },
                    res.data,
                    this.options
                    );
                }
            });
        },
        // 校区
        handelCampusChang(item) {
            this.teachingBuildingArr = []; // 教学楼
            this.query.towerCode = ''; // 教学楼
            let params = {
                campus: item
            };
            API.conditionQueryByDict(params).then(res => {
                _.forEach(res.data.list, item => {
                this.teachingBuildingArr.push({
                    value: item.code,
                    label: item.name
                });
                });
            });
        },
        downloadFile(command) {
            if (this.mark === 200) {
                // successive:依次排考
                if (command === 'successive') {
                    this.arrang.classrooms = []
                    this.arrang.campusList = []
                    this.arrang.competitionId = this.jsId
                    // console.log(this.dataList,'datalist');
                    this.dataList.forEach(item => {
                        this.arrang.classrooms.push({
                            'classroomId': item.id,
                            'roomSize': item.examCapacity,
                            'campus': item.campus,
                            'campusName': item.campusI18n,
                            'roomName': item.name,
                            'roomCode':item.roomCode
                        })
                    })
                    this.arrang.calendarId = this.dataObj.calendarId
                    this.arrang.realWeek = this.dataObj.realWeek
                    this.arrang.realWeekDay = this.dataObj.realWeekDay
                    this.arrang.classNodes = this.dataObj.classNodes
                    this.arrang.arrangeType = '0'
                    this.options.campus.forEach(item => {
                        this.arrang.campusList.push({
                            'code': item.value,
                            'name': item.label       
                        })
                    })
                    // this.dataList.forEach(item => {
                    //     this.arrang.campusList.push({
                    //         'code': item.campus,
                    //         'name': item.campusI18n
                    //     })
                    // })
                    if (this.dataList.length === 0) {
                        return this.$message.error(this.$t('arrangingExaminations.pleaseAddBackExam')) // 请添加教室后排考
                    }
                    for (let i = 0 ;i<this.dataList.length;i++) {
                        if (this.dataList[i].roomCode === '' || !this.dataList[i].roomCode) {
                            return this.$message.error(this.$t('arrangingExaminations.pleaseEnterExamRoom')) // 请输入考场号
                        }
                    }
                    for (let i = 0; i < this.dataList.length-1; i++) {
                        for (let j = i+1; j < this.dataList.length;j++){
                            if (this.dataList[i].roomCode === this.dataList[j].roomCode) {
                                return this.$message.error(this.$t('arrangingExaminations.ExamRoomCannotEnteredRepeatedly')) // 考场号不能重复输入
                            }
                        }
                    }
                    competitionRuleApi.arrange(this.arrang).then(res => {
                        if (res.code === 200) {
                            this.$message.success(this.$t('internship.successfully'));
                            this.getFreeClassroomInfoList();
                            competitionRuleApi.getSignedAndArrangedNum(this.jsId).then(res => {
                                // if (res.code === 200) {
                                //     this.compile = 'arrange'
                                    this.dataNumber = res.data
                                //     this.indexKey = 6
                                // }
                            })
                            // 排考完应对下面的表格“已排考”数据回显
                            let resXdata = []
                            competitionRuleApi.getArrangeClassroomInfo(this.jsId).then(res => {
                                if (res.code === 200) {
                                    resXdata = res.data
                                    for (let i = 0;i < resXdata.length; i++) {
                                        if (resXdata && resXdata.length > 0) {
                                            this.dataList[i].arrangeExam = resXdata[i].studentNum
                                            // 对上面“已排考人数”数据回显
                                            // this.dataNumber[1] = resXdata[i].studentNum
                                        }
                                    }
                                }
                            })
                            // isArrange 排考时间 
                            comRegistration.getDetail(this.jsId).then(res => {
                                this.isArrange = res.data.arrangeFinish
                            })
                            // console.log(this.isArrange,'ssssssssssdadasd');
                        }
                    })
                } else if (command === 'random') { // random:随机排考
                    this.arrang.classrooms = []
                    this.arrang.campusList = []
                    this.arrang.competitionId = this.jsId
                    this.dataList.forEach(item => {
                        this.arrang.classrooms.push({
                            'classroomId': item.id,
                            'roomSize': item.examCapacity,
                            'campus': item.campus,
                            'campusName': item.campusI18n,
                            'roomName': item.name,
                            'roomCode':item.roomCode
                        })
                    })
                    this.arrang.calendarId = this.dataObj.calendarId
                    this.arrang.realWeek = this.dataObj.realWeek
                    this.arrang.realWeekDay = this.dataObj.realWeekDay
                    this.arrang.classNodes = this.dataObj.classNodes
                    this.arrang.arrangeType = '1'
                    this.options.campus.forEach(item => {
                        this.arrang.campusList.push({
                            'code': item.value,
                            'name': item.label     
                        })
                    })
                    if (this.dataList.length === 0) {
                        return this.$message.error(this.$t('arrangingExaminations.pleaseAddBackExam')) // 请添加教室后排考
                    }
                    for (let i = 0; i < this.dataList.length; i++) {
                        if (this.dataList[i].roomCode === '' || !this.dataList[i].roomCode) {
                            return this.$message.error(this.$t('arrangingExaminations.pleaseEnterExamRoom')) // 请输入考场号
                        }
                    }
                    for (let i = 0;i < this.dataList.length-1; i++) {
                        for (let j = i+1; j < this.dataList.length; j++) {
                            if (this.dataList[i].roomCode === this.dataList[j].roomCode) {
                                return this.$message.error(this.$t('arrangingExaminations.ExamRoomCannotEnteredRepeatedly')) // 考场号不能重复输入
                            }
                        }
                    }
                    competitionRuleApi.arrange(this.arrang).then(res => {
                        if (res.code === 200) {
                            this.$message.success(this.$t('internship.successfully'));
                            this.getFreeClassroomInfoList();
                            competitionRuleApi.getSignedAndArrangedNum(this.jsId).then(res => {
                                // if (res.code === 200) {
                                //     this.compile = 'arrange'
                                    this.dataNumber = res.data
                                //     this.indexKey = 6
                                // }
                            })
                            // 排考完应对下面的表格“已排考”数据回显
                            let resXdata = []
                            competitionRuleApi.getArrangeClassroomInfo(this.jsId).then(res => {
                                if (res.code === 200) {
                                    resXdata = res.data
                                    // console.log(resXdata,'sssssssss');
                                    for (let i = 0 ;i < resXdata.length; i++) {
                                        if (resXdata && resXdata.length > 0) {
                                            this.dataList[i].arrangeExam = resXdata[i].studentNum
                                            // 对上面“已排考人数”数据回显
                                            // this.dataNumber[1] = resXdata[i].studentNum
                                        }
                                    }
                                }
                            })
                            // isArrange 排考时间 
                            comRegistration.getDetail(this.jsId).then(res => {
                                this.isArrange = res.data.arrangeFinish
                            })
                            // console.log(this.isArrange,'ssssssssssdadasd');
                        }
                    })
                } else if (command === 'teachClass') { // 按教学班排考
                    this.arrang.classrooms = []
                    this.arrang.campusList = []
                    this.arrang.competitionId = this.jsId
                    // console.log(this.dataList,'datalist');
                    this.dataList.forEach(item => {
                        this.arrang.classrooms.push({
                            'classroomId': item.id,
                            'roomSize': item.examCapacity,
                            'campus': item.campus,
                            'campusName': item.campusI18n,
                            'roomName': item.name,
                            'roomCode':item.roomCode
                        })
                    })
                    this.arrang.calendarId = this.dataObj.calendarId
                    this.arrang.realWeek = this.dataObj.realWeek
                    this.arrang.realWeekDay = this.dataObj.realWeekDay
                    this.arrang.classNodes = this.dataObj.classNodes
                    this.arrang.arrangeType = '2'
                    this.options.campus.forEach(item => {
                        this.arrang.campusList.push({
                            'code': item.value,
                            'name': item.label       
                        })
                    })
                    // this.dataList.forEach(item => {
                    //     this.arrang.campusList.push({
                    //         'code': item.campus,
                    //         'name': item.campusI18n
                    //     })
                    // })
                    if (this.dataList.length === 0) {
                        return this.$message.error(this.$t('arrangingExaminations.pleaseAddBackExam')) // 请添加教室后排考
                    }
                    for (let i = 0 ;i<this.dataList.length;i++) {
                        if (this.dataList[i].roomCode === '' || !this.dataList[i].roomCode) {
                            return this.$message.error(this.$t('arrangingExaminations.pleaseEnterExamRoom')) // 请输入考场号
                        }
                    }
                    for (let i = 0; i < this.dataList.length-1; i++) {
                        for (let j = i+1; j < this.dataList.length;j++){
                            if (this.dataList[i].roomCode === this.dataList[j].roomCode) {
                                return this.$message.error(this.$t('arrangingExaminations.ExamRoomCannotEnteredRepeatedly')) // 考场号不能重复输入
                            }
                        }
                    }
                    competitionRuleApi.arrange(this.arrang).then(res => {
                        if (res.code === 200) {
                            this.$message.success(this.$t('internship.successfully'));
                            this.getFreeClassroomInfoList();
                            competitionRuleApi.getSignedAndArrangedNum(this.jsId).then(res => {
                                // if (res.code === 200) {
                                //     this.compile = 'arrange'
                                    this.dataNumber = res.data
                                //     this.indexKey = 6
                                // }
                            })
                            // 排考完应对下面的表格“已排考”数据回显
                            let resXdata = []
                            competitionRuleApi.getArrangeClassroomInfo(this.jsId).then(res => {
                                if (res.code === 200) {
                                    resXdata = res.data
                                    for (let i = 0;i < resXdata.length; i++) {
                                        if (resXdata && resXdata.length > 0) {
                                            this.dataList[i].arrangeExam = resXdata[i].studentNum
                                            // 对上面“已排考人数”数据回显
                                            // this.dataNumber[1] = resXdata[i].studentNum
                                        }
                                    }
                                }
                            })
                            // isArrange 排考时间 
                            comRegistration.getDetail(this.jsId).then(res => {
                                this.isArrange = res.data.arrangeFinish
                            })
                            // console.log(this.isArrange,'ssssssssssdadasd');
                        }
                    })
                } else if (command === 'englishComArrange') { // 大英赛排考
                    this.arrang.classrooms = []
                    this.arrang.campusList = []
                    this.arrang.competitionId = this.jsId
                    // console.log(this.dataList,'datalist');
                    this.dataList.forEach(item => {
                        this.arrang.classrooms.push({
                            'classroomId': item.id,
                            'roomSize': item.examCapacity,
                            'campus': item.campus,
                            'campusName': item.campusI18n,
                            'roomName': item.name,
                            'roomCode':item.roomCode
                        })
                    })
                    this.arrang.calendarId = this.dataObj.calendarId
                    this.arrang.realWeek = this.dataObj.realWeek
                    this.arrang.realWeekDay = this.dataObj.realWeekDay
                    this.arrang.classNodes = this.dataObj.classNodes
                    this.arrang.arrangeType = '3'
                    this.options.campus.forEach(item => {
                        this.arrang.campusList.push({
                            'code': item.value,
                            'name': item.label       
                        })
                    })
                    // this.dataList.forEach(item => {
                    //     this.arrang.campusList.push({
                    //         'code': item.campus,
                    //         'name': item.campusI18n
                    //     })
                    // })
                    if (this.dataList.length === 0) {
                        return this.$message.error(this.$t('arrangingExaminations.pleaseAddBackExam')) // 请添加教室后排考
                    }
                    for (let i = 0 ;i<this.dataList.length;i++) {
                        if (this.dataList[i].roomCode === '' || !this.dataList[i].roomCode) {
                            return this.$message.error(this.$t('arrangingExaminations.pleaseEnterExamRoom')) // 请输入考场号
                        }
                    }
                    for (let i = 0; i < this.dataList.length-1; i++) {
                        for (let j = i+1; j < this.dataList.length;j++){
                            if (this.dataList[i].roomCode === this.dataList[j].roomCode) {
                                return this.$message.error(this.$t('arrangingExaminations.ExamRoomCannotEnteredRepeatedly')) // 考场号不能重复输入
                            }
                        }
                    }
                    competitionRuleApi.arrange(this.arrang).then(res => {
                        if (res.code === 200) {
                            this.$message.success(this.$t('internship.successfully'));
                            this.getFreeClassroomInfoList();
                            competitionRuleApi.getSignedAndArrangedNum(this.jsId).then(res => {
                                // if (res.code === 200) {
                                //     this.compile = 'arrange'
                                    this.dataNumber = res.data
                                //     this.indexKey = 6
                                // }
                            })
                            // 排考完应对下面的表格“已排考”数据回显
                            let resXdata = []
                            competitionRuleApi.getArrangeClassroomInfo(this.jsId).then(res => {
                                if (res.code === 200) {
                                    resXdata = res.data
                                    for (let i = 0;i < resXdata.length; i++) {
                                        if (resXdata && resXdata.length > 0) {
                                            this.dataList[i].arrangeExam = resXdata[i].studentNum
                                            // 对上面“已排考人数”数据回显
                                            // this.dataNumber[1] = resXdata[i].studentNum
                                        }
                                    }
                                }
                            })
                            // isArrange 排考时间 
                            comRegistration.getDetail(this.jsId).then(res => {
                                this.isArrange = res.data.arrangeFinish
                            })
                            // console.log(this.isArrange,'ssssssssssdadasd');
                        }
                    })
                }
            }
        }
    }
}
</script>
<style lang="scss" scoped>
::v-deep .distance {
    padding: 0 15px;
}
</style>